package logic

import (
	"context"
	"encoding/json"
	"manuscript-service/manrpc/manrpcclient"
	"manuscript-service/moders/cache"
	"manuscript-service/moders/mysql"
	"time"

	"manuscript-service/manrpc/internal/svc"
	"manuscript-service/manrpc/manrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ManuscriptListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewManuscriptListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ManuscriptListLogic {
	return &ManuscriptListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ManuscriptListLogic) ManuscriptList(in *manrpc.ManuscriptListRequest) (*manrpc.ManuscriptListResponse, error) {
	// todo: add your logic here and delete this line

	var manuscriptList []*manrpcclient.ManuscriptList
	result, _ := cache.Rdb.Get(l.ctx, "manuscriptList").Result()
	if result == "" {
		mysql.DB.Model(&mysql.Manuscript{}).
			Select("manuscripts.title",
				"manuscripts.price",
				"classes.`name`",
				"classes.id as class_id").
			Joins("LEFT JOIN classes ON classes.id = manuscripts.class_id").Find(&manuscriptList)
		marshal, _ := json.Marshal(manuscriptList)
		cache.Rdb.Set(l.ctx, "manuscriptList", marshal, time.Minute*120)
	} else {
		json.Unmarshal([]byte(result), &manuscriptList)
	}

	return &manrpc.ManuscriptListResponse{
		List: manuscriptList,
	}, nil
}
